package com.liu.juc.collection;

import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Set 线程安全
 * // java.util.ConcurrentModificationException
 */
public class UnsafeSetDemo {

    /**
     * HashSet:线程不安全 并发操作时：会抛出ConcurrentModificationException 并发修改异常
     * 解决方案;
     * 方案一：工具类 ： Collections.synchronizedSet(new HashSet<>());
     * 方案二：JUC: new CopyOnWriteArraySet<>()
     *
     * @param args
     */
    public static void main(String[] args) {
        // Set<String> sets = new HashSet<String>();
        // Set<String> sets = Collections.synchronizedSet(new HashSet<>());
        Set<String> sets = new CopyOnWriteArraySet<>();
        for (int i = 1; i <= 100; i++) {
            new Thread(() -> {
                sets.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(sets);
            }, String.valueOf(i)).start();

        }
    }
}
